package com.hck.weight_test.ObtainWeighing.device;

import android.util.Log;

import com.hck.weight_test.ObtainWeighing.WeightLogUtil;
import com.hck.weight_test.ObtainWeighing.bean.DeviceBean;
import com.hck.weight_test.ObtainWeighing.interfaces.IDevice;
import com.hck.weight_test.ObtainWeighing.interfaces.IDeviceGetDataListener;

public class DeviceReader extends Thread{
    private boolean isRunning = false;
    private DeviceBean deviceBean;
    private IDevice device;
    private IDeviceGetDataListener mGetDataListener;

    byte[] buffer = new byte[1024];

    public DeviceReader(DeviceBean deviceBean, IDevice device, IDeviceGetDataListener getDataListener) {
        this.deviceBean = deviceBean;
        this.device = device;
        this.mGetDataListener = getDataListener;
    }

    @Override
    public void run() {
        final DeviceBean device = this.deviceBean;
        final IDevice deviceConnection = this.device;
        isRunning = true;
        while (isRunning) {
            try {
                // 前置操作，和设备类型相关
                    byte[] cmd_get_weight = {0x02, 0x41, 0x48, 0x31, 0x03};//读取重量
                    deviceConnection.write(cmd_get_weight);
                    Thread.sleep(100);
                // 读数据

                int len = deviceConnection.read(buffer);
                if (len > 0) {
                    String data = new String(buffer, 0, len);
                   // Log.d("hck","获取数据1 "+data);
                    this.mGetDataListener.onGetData(device, data);
                    Thread.sleep(50);
                } else {
                    Thread.sleep(100);
                }
            } catch (Exception e) {
                WeightLogUtil.log("DeviceReader red: "+e);
            }
        }
    }
    public void cancel() {
        isRunning = false;
        this.device.close();
        this.deviceBean = null;
        this.device = null;
        this.mGetDataListener = null;
    }



}
